package com.springboot.learn_zookeeper.demo2;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 获取节点下的字节点及子节点的数据
 */
public class ZKGetChildren {
    private static ZooKeeper zk;
    private static ZooKeeperConnection conn;

    // Method to check existence of znode and its status, if znode is available.
    public static Stat znode_exists(String path) throws
            KeeperException,InterruptedException {
        return zk.exists(path,true);
    }
    public static void main(String[] args) throws InterruptedException,KeeperException {
        String path = "/MyFirstZnode"; // Assign path to the znode
        final CountDownLatch connectedSignal = new CountDownLatch(1);

        try {
            conn = new ZooKeeperConnection();
            zk = conn.connect("localhost");
            Stat stat = znode_exists(path); // Stat checks the path

            if(stat!= null) {
                List<String> children = zk.getChildren(path, false);
                for (int i = 0; i < children.size(); i++) {
                    System.out.println(children.get(i)); //Print children's
                    byte[] bn = zk.getData(path + "/" + children.get(i),
                            false, null);
                    String data = new String(bn,
                            "UTF-8");
                    System.out.println(data);
                    connectedSignal.countDown();
                }
            }else{
                System.out.println("Node does not exists");
            }

        } catch(Exception e) {
            System.out.println(e.getMessage());
        }

    }
}
